package login;

import login.ops.PKCS7SignatureOps;
import login.ops.SignatureContainerOps;
import login.ops.SignatureOps;
import org.slf4j.LoggerFactory;
import tr.gov.tubitak.uekae.esya.api.common.ESYAException;
import tr.gov.tubitak.uekae.esya.api.common.util.Base64;
import tr.gov.tubitak.uekae.esya.api.common.util.LicenseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Validation servlet for signatures in home page
 *
 * @author suleyman.uslu
 */
@WebServlet(name = "signServlet")
public class SignatureValidation extends HttpServlet {

    private static org.slf4j.Logger msLogger = LoggerFactory.getLogger(SignatureValidation.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String signature64 = request.getParameter("signature64");

        try {
            LicenseUtil.setLicenseXml(new FileInputStream(Util.licensePath));
        } catch (ESYAException e) {
            e.printStackTrace();
        }

        byte[] signatureBytes = Base64.decode(signature64);

        SignatureOps signatureOps = null;
        boolean isValid = false;

        // create operation object for correct type of signature
        switch(Util.signatureType) {
            //case XAdES : signatureOps = new XmlSignatureOps(signatureBytes);    break;
            //case CAdES : signatureOps = new CmsSignatureOps(signatureBytes);    break;
            case Container : signatureOps = new SignatureContainerOps(signatureBytes);  break;
            case PKCS7 : signatureOps = new PKCS7SignatureOps(signatureBytes);    break;
        }

        // validate signature
        isValid = signatureOps.verify();

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if(isValid) {

            //session.setAttribute("MESSAGE", "Signature is validated");

            user.setMessage("Signature is validated");
            session.setAttribute("user", user);

            request.getRequestDispatcher("home.jsp").forward(request,response);
        }
        else {

            //session.setAttribute("MESSAGE", "Signature cannot be validated!");

            user.setMessage("Signature cannot be validated");
            session.setAttribute("user", user);

            request.getRequestDispatcher("home.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
